<template>
  <div class="app-wrapper app-table-wrapper">
    <div class="global-search-wrapper">
      <div class="search-item">
        <div class="left">
          <custom-button type="green" :disabled="disabled" @click="updateRowProperty('isPublic', true)">
            设为公开展示
          </custom-button>
          <custom-button type="red" :disabled="disabled" @click="updateRowProperty('isPublic', false)">
            禁止公开展示
          </custom-button>
          <custom-button type="green" :disabled="disabled" @click="updateRowProperty('isHot', true)">
            设为 HOT
          </custom-button>
          <custom-button type="red" :disabled="disabled" @click="updateRowProperty('isHot', false)">
            取消 HOT
          </custom-button>
          <custom-button type="blue" :disabled="disabled" @click="orderIndexVisible = true">修改排序参数</custom-button>
        </div>
        <el-input
          v-model="keyword"
          class="primary-input margin-right-sm"
          placeholder="输入id/标题/作者用户名"
          clearable
          @keydown.enter.stop="fetchData"
        ></el-input>
      </div>
    </div>
    <el-table class="margin-top-lg" border row-key="id" :data="data" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="id" prop="id" align="center" />
      <el-table-column label="uuid" prop="uuid" align="center" />
      <el-table-column label="标题" prop="title" align="center" />
      <el-table-column label="缩略图" prop="coverImg" align="center">
        <template #default="{ row }">
          <el-link v-if="row.coverImg" type="primary" :href="row.coverImg" target="_blank">查看缩略图</el-link>
        </template>
      </el-table-column>
      <el-table-column label="作者用户名" prop="author" align="center" />
      <el-table-column label="查看网页" align="center">
        <template #default="{ row }">
          <!-- 状态：0-删除 1-未发布 2-发布 3-管理员强制下线 -->
          <el-link
            v-if="row.status === 1"
            :href="`${baseH5URL}/p/preview/${row.id}-${row.uuid}`"
            target="_blank"
            type="primary"
          >
            预览
          </el-link>
          <el-link
            v-else-if="row.status === 2"
            :href="`${baseH5URL}/p/${row.id}-${row.uuid}?channel=0`"
            target="_blank"
            type="primary"
          >
            线上链接
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="使用次数" prop="copiedCount" align="center" />
      <el-table-column label="公开展示" align="center">
        <template #default="{ row }">
          <span>{{ row.isPublic ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center">
        <template #default="{ row }">
          <span v-if="row.isHot"><el-tag type="danger" :effect="isDark ? 'dark' : 'light'">HOT</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column label="排序参数" prop="orderIndex" align="center" />
      <el-table-column label="创建时间" prop="createdAt" align="center" />
    </el-table>
    <pagination
      v-model:size="searchParams.pageSize"
      v-model:page="searchParams.pageIndex"
      class="margin-top-lg"
      :total="total"
      @pagination="fetchData"
    />

    <el-dialog v-model="orderIndexVisible" width="500" title="修改排序参数">
      <el-form>
        <el-form-item label="orderIndex" label-width="100px">
          <el-input v-model="orderIndexInput" style="width: 120px" autocomplete="off" />
          <span>（请输入 0-10 整数）</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="orderIndexVisible = false">取消</el-button>
          <el-button
            type="primary"
            :disabled="inputDisabled"
            @click="updateRowProperty('orderIndex', parseInt(orderIndexInput))"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { WorkDataProps } from '@/service/request'
import { fetchTemplates, updateHot, updatePublic, updateOrderIndex } from '@/service/template'
import { ElMessage } from 'element-plus'
import { useGlobalStore } from '@/stores/global'

const baseH5URL = import.meta.env.VITE_BASE_H5_URL
const global = useGlobalStore()

const data = ref<WorkDataProps[]>([])
const total = ref(0)
const keyword = ref('')
const selectRows = ref<WorkDataProps[]>([])
const disabled = computed(() => selectRows.value.length === 0)
const isDark = computed(() => global.isDark)

const orderIndexVisible = ref(false)
const orderIndexInput = ref('')
const inputDisabled = computed(() => {
  if (!Number.isFinite(parseInt(orderIndexInput.value))) {
    return true
  }
  return false
})

const searchParams = computed(() => ({
  pageIndex: 1,
  pageSize: 10,
  keyword: keyword.value
}))

onMounted(async () => {
  await fetchData()
})

async function fetchData() {
  const { list, count } = await fetchTemplates(searchParams.value)
  data.value = list
  total.value = count
}

function handleSelectionChange(list: WorkDataProps[]) {
  selectRows.value = [...list]
  console.log(selectRows.value)
}

async function updateRowProperty(type: 'isHot' | 'isPublic' | 'orderIndex', value: boolean | number) {
  const ids = selectRows.value
    .map(item => {
      return item.id
    })
    .join(',')
  switch (type) {
    case 'isHot':
      await updateHot({ ids, isHot: value as boolean })
      break
    case 'isPublic':
      await updatePublic({ ids, isPublic: value as boolean })
      break
    case 'orderIndex':
      await updateOrderIndex({ ids, orderIndex: value as number })
      orderIndexVisible.value = false
      orderIndexInput.value = ''
      break
  }
  ElMessage.success('变更成功')
  await fetchData()
}
</script>
<style lang="scss" scoped></style>
